const { spawn } = require('child_process')
const MAX_MEMORY = 8192 // 8GB
const RESTART_THRESHOLD = 7680 // 7.5GB

function startServer() {
  console.log('启动 VitePress 开发服务器...')
  const child = spawn(
    'node',
    [`--max-old-space-size=${MAX_MEMORY}`, 'node_modules/vitepress/bin/vitepress.js', 'dev'],
    { stdio: 'inherit' }
  )

  // 定时检查内存
  const memoryCheck = setInterval(() => {
    const used = process.memoryUsage()

    // console.log(used.heapUsed / 1024 / 1024, RESTART_THRESHOLD)
    // console.log(child)

    // console.log(
    //   `内存使用: RSS ${Math.round(used.rss / 1024 / 1024)}MB, Heap ${Math.round(
    //     used.heapUsed / 1024 / 1024
    //   )}MB / ${Math.round(used.heapTotal / 1024 / 1024)}MB`
    // )

    if (used.heapUsed / 1024 / 1024 > RESTART_THRESHOLD) {
      console.log('内存接近上限，准备重启...')
      clearInterval(memoryCheck)
      child.kill()
      setTimeout(startServer, 1000)
    }
  }, 30000)

  child.on('close', (code) => {
    clearInterval(memoryCheck)
    if (code === 0) {
      console.log('服务器正常退出')
    } else {
      console.log('服务器异常退出，准备重启...')
      setTimeout(startServer, 2000)
    }
  })
}

startServer()
